#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "nvs.h"
#include "esp_log.h"
#include "my_json_parse.h"

static const char *TAG = "dev_info";

/* 储存设备上电次数(第一次或不是第一次) */
esp_err_t first_start_write(uint8_t dev_first) {
	nvs_handle_t my_handle;
	esp_err_t err = nvs_open("my_dev_first", NVS_READWRITE, &my_handle);
	if (err != ESP_OK) {
        ESP_LOGE(TAG,"open failed\n");
        return err;
	} 
    else {
		err = nvs_set_u8(my_handle, "dev_first", !!dev_first); /* set 不需要使用地址 */

		err = nvs_commit(my_handle);

		nvs_close(my_handle);
	}

	return err;
}

/*　读取设备上电次数(第一次或不是第一次)　*/
esp_err_t first_start_read(uint8_t *dev_first) {
	if (NULL == dev_first) {
		return ESP_FAIL;
	}
	nvs_handle my_handle;
	esp_err_t err = nvs_open("my_dev_first", NVS_READWRITE, &my_handle);
	if (err != ESP_OK) {
		ESP_LOGE(TAG,"Error opening NVS handle inside miio_dev_info_read!\n");
	} else {
		*dev_first = 0;	/* 如果nvs没有初始化，则设置默认值0 */
		err = nvs_get_u8(my_handle, "dev_first", dev_first); /* get 需要使用地址 */
		switch (err) {
		case ESP_OK:
			break;
		case ESP_ERR_NVS_NOT_FOUND:
			break;
		default:
			;
		}
	}

	nvs_close(my_handle);
	return err;
}


/* 存储web服务器配置的节点参数 */
esp_err_t write_note_data(note_json note_json_t) {
	nvs_handle_t my_handle;
	esp_err_t err = nvs_open("note_data", NVS_READWRITE, &my_handle);
	if (err != ESP_OK) {
        ESP_LOGE(TAG,"open failed\n");
        return err;
	} 
    else {
		err = nvs_set_str(my_handle, "app_key", note_json_t.app_key);
		err = nvs_commit(my_handle);
		nvs_close(my_handle);
	}

	return err;
}

/* 读取web服务器配置的note参数 */
esp_err_t read_note_data(note_json *note_json_p) {
	if (NULL == note_json_p) {
		return ESP_FAIL;
	}
	nvs_handle my_handle;

	size_t appkey_len = sizeof(note_json_p->app_key);


	esp_err_t err = nvs_open("note_data", NVS_READWRITE, &my_handle);
	if (err != ESP_OK) {
		ESP_LOGE(TAG,"Error opening NVS handle inside read_note_data!\n");
	} else {
		err = nvs_get_str(my_handle, "app_key", note_json_p->app_key, &appkey_len);
		switch (err) {
		case ESP_OK:
			break;
		case ESP_ERR_NVS_NOT_FOUND:
			break;
		default:
			;
		}
	}

	nvs_close(my_handle);
	return err;
}


/* 存储web服务器配置的AP参数 */
esp_err_t write_ap_data(ap_json ap_json_t) {
	nvs_handle_t my_handle;
	esp_err_t err = nvs_open("ap_data", NVS_READWRITE, &my_handle);
	if (err != ESP_OK) {
        ESP_LOGE(TAG,"open failed\n");
        return err;
	} 
    else {
		err = nvs_set_str(my_handle, "authmode", ap_json_t.authmode);
		err = nvs_set_u8(my_handle, "channel", ap_json_t.channel);
		err = nvs_set_str(my_handle, "ssid", ap_json_t.ssid);
		err = nvs_set_str(my_handle, "passwd", ap_json_t.passwd);

		err = nvs_commit(my_handle);
		nvs_close(my_handle);
	}

	return err;
}


/* 读取web服务器配置的AP参数 */
esp_err_t read_ap_data(ap_json *ap_json_p) {
	if (NULL == ap_json_p) {
		return ESP_FAIL;
	}
	nvs_handle my_handle;
	size_t authmode_len = sizeof(ap_json_p->authmode);
	size_t ssid_len = sizeof(ap_json_p->ssid);
	size_t passwd_len = sizeof(ap_json_p->passwd);

	esp_err_t err = nvs_open("ap_data", NVS_READWRITE, &my_handle);
	if (err != ESP_OK) {
		ESP_LOGE(TAG,"Error opening NVS handle inside read_ap_data!\n");
	} else {
		
		err = nvs_get_str(my_handle, "authmode", ap_json_p->authmode, &authmode_len);
		err = nvs_get_u8(my_handle, "channel", &ap_json_p->channel);
		err = nvs_get_str(my_handle, "ssid", ap_json_p->ssid, &ssid_len);
		err = nvs_get_str(my_handle, "passwd", ap_json_p->passwd, &passwd_len);

		switch (err) {
		case ESP_OK:
			break;
		case ESP_ERR_NVS_NOT_FOUND:
			break;
		default:
			;
		}
	}

	nvs_close(my_handle);
	return err;
}





/* 存储web服务器配置的MQTT client参数 */
esp_err_t write_mqtt_client_data(mqtt_client_parameter mqtt_client_t) {
	nvs_handle_t my_handle;
	esp_err_t err = nvs_open("mqtt_client", NVS_READWRITE, &my_handle);
	if (err != ESP_OK) {
        ESP_LOGE(TAG,"open failed\n");
        return err;
	} 
    else {
		// printf("write sub = %s\n",mqtt_client_t.subscribe_topic);
		err = nvs_set_str(my_handle, "host", mqtt_client_t.host);
		err = nvs_set_str(my_handle, "sub", mqtt_client_t.subscribe_topic);
		err = nvs_set_str(my_handle, "pub", mqtt_client_t.public_topic);
		err = nvs_set_str(my_handle, "username", mqtt_client_t.username);
		err = nvs_set_str(my_handle, "passwd", mqtt_client_t.passwd);
		err = nvs_set_u8(my_handle,  "qos", mqtt_client_t.qos);
		err = nvs_set_u32(my_handle, "port", mqtt_client_t.port);
		err = nvs_set_u32(my_handle, "heart", mqtt_client_t.heartbeat);
		err = nvs_set_u8(my_handle,  "autoconnect", mqtt_client_t.autoconnect);

		err = nvs_commit(my_handle);
		nvs_close(my_handle);
	}

	return ESP_OK;
}


#include <string.h>
/* 读取web服务器配置的MQTT client参数 */
esp_err_t read_mqtt_client_data(mqtt_client_parameter *mqtt_client_p) {
	if (NULL == mqtt_client_p) {
		return ESP_FAIL;
	}
	nvs_handle my_handle;
	size_t host_len = sizeof(mqtt_client_p->host);
	size_t sub_len = sizeof(mqtt_client_p->subscribe_topic);
	size_t pub_len = sizeof(mqtt_client_p->public_topic);
	size_t username_len = sizeof(mqtt_client_p->username);
	size_t passwd_len = sizeof(mqtt_client_p->passwd);

	esp_err_t err = nvs_open("mqtt_client", NVS_READWRITE, &my_handle);
	if (err != ESP_OK) {
		ESP_LOGE(TAG,"Error opening NVS handle inside read_mqtt_client_data!\n");
	} else {
		strcpy((char*)mqtt_client_p->host, "111.230.203.185");
		strcpy((char*)mqtt_client_p->username, "admin");
		strcpy((char*)mqtt_client_p->passwd, "public");
		strcpy((char*)mqtt_client_p->subscribe_topic, "sub_aithinker");
		strcpy((char*)mqtt_client_p->public_topic, "pub_aithinker");
		// mqtt_client_p->host = "111.230.203.185";
		// mqtt_client_p->username = "admin";
		// mqtt_client_p->passwd = "public";
		// mqtt_client_p->subscribe_topic = "sub_aithinker";
		// mqtt_client_p->public_topic = "pub_aithinker";
		mqtt_client_p->qos = 1;
		mqtt_client_p->port = 1883;
		mqtt_client_p->heartbeat = 60;
		mqtt_client_p->autoconnect = 0;		//0－重连　１－不重连

		err = nvs_get_str(my_handle, "host", mqtt_client_p->host, &host_len);
		err = nvs_get_str(my_handle, "sub", mqtt_client_p->subscribe_topic, &sub_len);
		err = nvs_get_str(my_handle, "pub", mqtt_client_p->public_topic, &pub_len);
		err = nvs_get_str(my_handle, "username", mqtt_client_p->username, &username_len);
		err = nvs_get_str(my_handle, "passwd", mqtt_client_p->passwd, &passwd_len);
		err = nvs_get_u8(my_handle, "qos", &mqtt_client_p->qos);
		err = nvs_get_u32(my_handle, "port", &mqtt_client_p->port);
		err = nvs_get_u32(my_handle, "heart", &mqtt_client_p->heartbeat);
		err = nvs_get_u8(my_handle, "autoconnect", &mqtt_client_p->autoconnect);
		// printf("read sub =　%s\n",mqtt_client_p->subscribe_topic);

		switch (err) {
		case ESP_OK:
			break;
		case ESP_ERR_NVS_NOT_FOUND:
			break;
		default:
			;
		}
	}

	nvs_close(my_handle);
	return err;
}








esp_err_t erase_flash_data(void)
{
	nvs_handle my_handle;
	//ap_json数据
    esp_err_t err = nvs_open("ap_data", NVS_READWRITE, &my_handle);
    if (err == ESP_OK) {
		
        err = nvs_erase_key(my_handle, "authmode");
		err = nvs_erase_key(my_handle, "channel");
		err = nvs_erase_key(my_handle, "ssid");
		err = nvs_erase_key(my_handle, "passwd");
        if (err == ESP_OK) {
            err = nvs_commit(my_handle);
            if (err == ESP_OK) {
                ESP_LOGI(TAG, "Value with key ap_data erased");
            }
        }
        nvs_close(my_handle);
    }
	//设备上电次数数据
	err = nvs_open("my_dev_first", NVS_READWRITE, &my_handle);
	 if (err == ESP_OK) {
		
        err = nvs_erase_key(my_handle, "dev_first");
        if (err == ESP_OK) {
            err = nvs_commit(my_handle);
            if (err == ESP_OK) {
                ESP_LOGI(TAG, "Value with key my_dev_first erased");
            }
        }
        nvs_close(my_handle);
    }
	
	//设备工作模式
	err = nvs_open("work_model", NVS_READWRITE, &my_handle);
	 if (err == ESP_OK) {
		
        err = nvs_erase_key(my_handle, "dev_model");
        if (err == ESP_OK) {
            err = nvs_commit(my_handle);
            if (err == ESP_OK) {
                ESP_LOGI(TAG, "Value with key work_model erased");
            }
        }
        nvs_close(my_handle);
    }

	//mqtt配置
	err = nvs_open("mqtt_client", NVS_READWRITE, &my_handle);
    if (err == ESP_OK) {
        err = nvs_erase_key(my_handle, "host");
		err = nvs_erase_key(my_handle, "sub");
		err = nvs_erase_key(my_handle, "pub");
		err = nvs_erase_key(my_handle, "username");
		err = nvs_erase_key(my_handle, "passwd");
		err = nvs_erase_key(my_handle, "qos");
		err = nvs_erase_key(my_handle, "port");
		err = nvs_erase_key(my_handle, "heart");
		err = nvs_erase_key(my_handle, "autoconnect");
        if (err == ESP_OK) {
            err = nvs_commit(my_handle);
            if (err == ESP_OK) {
                ESP_LOGI(TAG, "Value with key mqtt_client erased");
            }
        }
        nvs_close(my_handle);
    }

	//节点配置
	err = nvs_open("note_data", NVS_READWRITE, &my_handle);
    if (err == ESP_OK) {
		err = nvs_erase_key(my_handle, "app_key");
		if (err == ESP_OK) {
            err = nvs_commit(my_handle);
            if (err == ESP_OK) {
                ESP_LOGI(TAG, "Value with key mqtt_client erased");
            }
        }
        nvs_close(my_handle);
	}
    return err;
}





/* 储存工作模式(蓝牙网关｜WIFI网关) */
esp_err_t write_dev_work_model(uint8_t dev_work_model) {
	nvs_handle_t my_handle;
	esp_err_t err = nvs_open("work_model", NVS_READWRITE, &my_handle);
	if (err != ESP_OK) {
        ESP_LOGE(TAG,"open failed\n");
        return err;
	} 
    else {
		err = nvs_set_u8(my_handle, "dev_model", dev_work_model); /* set 不需要使用地址 */

		err = nvs_commit(my_handle);

		nvs_close(my_handle);
	}

	return err;
}

/*　读取工作模式(蓝牙网关｜WIFI网关)　*/
esp_err_t read_dev_work_model(uint8_t *dev_work_model) {
	if (NULL == dev_work_model) {
		return ESP_FAIL;
	}
	nvs_handle my_handle;
	esp_err_t err = nvs_open("work_model", NVS_READWRITE, &my_handle);
	if (err != ESP_OK) {
		ESP_LOGE(TAG,"Error opening NVS handle inside read_dev_work_model!\n");
	} else {
		*dev_work_model = 1;	/* 如果nvs没有初始化，则设置默认值1 */
		err = nvs_get_u8(my_handle, "dev_model", dev_work_model); /* get 需要使用地址 */
		switch (err) {
		case ESP_OK:
			break;
		case ESP_ERR_NVS_NOT_FOUND:
			break;
		default:
			;
		}
	}

	nvs_close(my_handle);
	return err;
}













#include <string.h>



void my_printf(mqtt_client_parameter mqtt_client_t)
{
    printf("host = %s\n",mqtt_client_t.host);
    printf("port = %d\n", mqtt_client_t.port);
    printf("sub = %s\n",mqtt_client_t.subscribe_topic);
    printf("pub = %s\n",mqtt_client_t.public_topic); 
    printf("username = %s\n",mqtt_client_t.username);
    printf("passwd = %s\n",mqtt_client_t.passwd);
	printf("qos = %d\n",mqtt_client_t.qos);
	printf("heart = %d\n",mqtt_client_t.heartbeat);
	printf("autoconnect = %d\n",mqtt_client_t.autoconnect);
    // ESP_LOGI(TAG,"host = %s\n",mqtt_client_t.host);
    // ESP_LOGI(TAG,"port = %d\n", mqtt_client_t.port);
    // ESP_LOGI(TAG,"sub = %s\n",mqtt_client_t.subscribe_topic);
    // ESP_LOGI(TAG,"pub = %s\n",mqtt_client_t.public_topic); 
    // ESP_LOGI(TAG,"username = %s\n",mqtt_client_t.username);
    // ESP_LOGI(TAG,"passwd = %s\n",mqtt_client_t.passwd);
    return;
}








esp_err_t test_read(void)
{
	nvs_handle my_handle;
	const char str[] = "value 0123456789abcdef0123456789abcdef";
	esp_err_t err = nvs_open("ap_data", NVS_READWRITE, &my_handle);
    
	nvs_set_str(my_handle, "key", str);

	char buf[strlen(str) + 1];
    size_t buf_len = sizeof(buf);
	err = nvs_get_str(my_handle, "key", buf, &buf_len);
	printf("%s\n",buf);
	nvs_close(my_handle);
	return err;
}


// /* 判断是否第一次启动 */
// esp_err_t miio_first_start_write(uint8_t dev_first) {
// 	nvs_handle my_handle;
// 	esp_err_t err = nvs_open("miio_dev_first", NVS_READWRITE, &my_handle);
// 	if (err != ESP_OK) {

// 	} else {
// 		err = nvs_set_u8(my_handle, "dev_first", !!dev_first); /* set 不需要使用地址 */

// 		err = nvs_commit(my_handle);

// 		nvs_close(my_handle);
// 	}

// 	return err;
// }

// esp_err_t miio_first_start_read(uint8_t *dev_first) {
// 	if (NULL == dev_first) {
// 		return MIIO_ERROR;
// 	}

// 	nvs_handle my_handle;
// 	esp_err_t err = nvs_open("miio_dev_first", NVS_READWRITE, &my_handle);
// 	if (err != ESP_OK) {
// 		printf("Error opening NVS handle inside miio_dev_info_read!\n");
// 	} else {
// 		*dev_first = 0;	/* 如果nvs没有初始化，则设置默认值0 */
// 		err = nvs_get_u8(my_handle, "dev_first", dev_first); /* get 需要使用地址 */
// 		switch (err) {
// 		case ESP_OK:
// 			break;
// 		case ESP_ERR_NVS_NOT_FOUND:
// 			break;
// 		default:
// 			;
// 		}
// 	}

// 	nvs_close(my_handle);

// 	return err;
// }